import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Button, Icon, Modal, notification, Switch, Tooltip, Upload, Input, List} from "antd";

import {
    getBusinessCodeList,
    getCarrierList,
    getClientList2,
    getCurrencyList,
    getFeeList,
    getMyColumns,
    importZadOrder,
    importZadOrderFee, importZadOrderTransportFee,
    lock,
    openFollowChange,
    query,
    showColumns,
    showCreate,
    unlock,
    updateDataSource
} from "./actions";
import {getCurrentOrganization, getOpenFollow, getPrincipal, setOpenFollow} from "../../lib/identity";
import lodash from 'lodash';

const {TextArea} = Input;

class Toolbar extends PureComponent {
    state = {daiBan: false, openFollow: false, visible: false, dataList: []};
    handleShowCreate = () => {
        const {dispatch} = this.props;
        dispatch(showCreate());
        dispatch(getFeeList());
        dispatch(getClientList2(getCurrentOrganization()));
        dispatch(getCarrierList());
        dispatch(getCurrencyList());
        dispatch(getFeeList());
        dispatch(getBusinessCodeList());
    };

    handleShowColumns = () => {
        const {dispatch} = this.props;
        dispatch(getMyColumns("zadOrder"));
        dispatch(showColumns());
    };

    handleExportTransportFee = () => {
        const {selectedRowKeys} = this.props;
        if (selectedRowKeys.length > 0) {
            document.getElementById("idsExportTransportFee").value = lodash.join(selectedRowKeys, ",");
            document.getElementById("exportTransportFeeBySelect").submit();
            notification.success({
                message: '请等待文件导出'
            });
        } else {
            document.getElementById("exportTransportFee").submit();
            notification.success({
                message: '请等待文件导出'
            });
        }
    };

    handleCancelModal = () => {
        this.setState({visible: false, dataList: []});
    };

    handleLock = () => {
        const {dispatch, selectedRowKeys, dataSource} = this.props;
        dispatch(lock(selectedRowKeys)).then(action => {
            if (action.error !== true) {
                for (var i = 0; i < selectedRowKeys.length; i++) {
                    const found = dataSource.find(item => item.id === selectedRowKeys[i]);
                    if (found) {
                        found.status = "CONFIRMED";
                    }
                }
                dispatch(updateDataSource([...dataSource]));
                notification.success({
                    message: '锁定成功'
                });
            } else {
                notification.error({
                    message: '锁定失败:' + action.message
                });
            }
        });
    };

    handleUnlock = () => {
        const {dispatch, selectedRowKeys, dataSource} = this.props;
        dispatch(unlock(selectedRowKeys)).then(action => {
            if (action.error !== true) {
                for (var i = 0; i < selectedRowKeys.length; i++) {
                    const found = dataSource.find(item => item.id === selectedRowKeys[i]);
                    if (found) {
                        found.status = "UN_CONFIRM";
                    }
                }
                dispatch(updateDataSource([...dataSource]));
                notification.success({
                    message: '解锁成功'
                });
            } else {
                notification.error({
                    message: '解锁失败:' + action.message
                });
            }
        });
    };

    onChangeFollow = (value, e) => {
        const {dispatch} = this.props;
        dispatch(openFollowChange(value));
        setOpenFollow(value);
    };

    onChangeDaiBan = (value, e) => {
        const {dispatch, filter} = this.props;
        this.setState({daiBan: value});
        const daiBan = value ? "daiBan" : "";
        dispatch(query({
            ...filter, "userId": getPrincipal().id, "organizationId": getCurrentOrganization(), orderDaiBan: daiBan
        }));
    };

    handleExportBySelect = () => {
        const {selectedRowKeys} = this.props;
        document.getElementById("ids").value = lodash.join(selectedRowKeys, ",");
        document.getElementById("exportBySelect").submit();
        notification.success({
            message: '请等待文件导出'
        });
    };

    handleExportFeeExcel = () => {
        document.getElementById("downloadFeeExcel").submit();
        notification.success({
            message: '请等待文件导出'
        });
    };

    handleExport = () => {
        document.getElementById("export").submit();
        notification.success({
            message: '请等待文件导出'
        });
    };

    customRequest = (options) => {
        const {dispatch, filter} = this.props;
        dispatch(importZadOrder({
            file: options.file,
            opId: getPrincipal().id
        })).then(action => {
            if (action.payload.length === 0) {
                notification.success({
                    message: '导入成功'
                });
            } else {
                this.setState({visible: true, dataList: action.payload || []});
            }
            const daiBan = this.state.daiBan ? "daiBan" : "";
            dispatch(query({
                ...filter, "userId": getPrincipal().id, "organizationId": getCurrentOrganization(), orderDaiBan: daiBan
            }));
        });
    };
    customFeeRequest = (options) => {
        const {dispatch, filter} = this.props;
        dispatch(importZadOrderFee({
            file: options.file,
            opId: getPrincipal().id
        })).then(action => {
            if (action.payload.length === 0) {
                notification.success({
                    message: '导入费用成功'
                });
            } else {
                this.setState({visible: true, dataList: action.payload || []});
            }
            const daiBan = this.state.daiBan ? "daiBan" : "";
            dispatch(query({
                ...filter, "userId": getPrincipal().id, "organizationId": getCurrentOrganization(), orderDaiBan: daiBan
            }));
        });
    };
    customTransportFeeRequest = (options) => {
        const {dispatch, filter} = this.props;
        dispatch(importZadOrderTransportFee({
            file: options.file,
            opId: getPrincipal().id
        })).then(() => {
            notification.success({
                message: '导入运费成功'
            });
            const daiBan = this.state.daiBan ? "daiBan" : "";
            dispatch(query({
                ...filter, "userId": getPrincipal().id, "organizationId": getCurrentOrganization(), orderDaiBan: daiBan
            }));
        });
    };
    uploadProps = {
        showUploadList: false,
        name: 'file',
        accept: '.xls, .xlsx, .csv',
        customRequest: this.customRequest
    };

    uploadFeeProps = {
        showUploadList: false,
        name: 'file',
        accept: '.xls, .xlsx, .csv',
        customRequest: this.customFeeRequest
    };

    uploadTransportFeeProps = {
        showUploadList: false,
        name: 'file',
        accept: '.xls, .xlsx, .csv',
        customRequest: this.customTransportFeeRequest
    };

    render() {
        const {openFollow, filter = {}, columns, importLoading} = this.props;
        const data = [];
        delete filter.userId;
        for (let key of Object.keys(filter)) {
            const value = filter[key];
            if (value === undefined) {
                continue;
            }
            data.push({"key": key, "value": value});
        }
        return (
            <div className="actions">
                <Button onClick={this.handleShowCreate}><Icon type="plus"/>新增</Button>
                <Button onClick={this.handleShowColumns}><Icon type="ordered-list"/>自定义列</Button>
                <Button href="/static/国际班列导入模板.xlsx" target="_blank">下载导入模板</Button>
                <Upload {...this.uploadProps}>
                    <Button disabled={importLoading}>
                        <Icon type="upload"/> 导入
                    </Button>
                </Upload>
                <Button onClick={this.handleExportFeeExcel}>下载费用导入模板</Button>
                <Upload {...this.uploadFeeProps}>
                    <Button disabled={importLoading}>
                        <Icon type="upload"/> 导入费用
                    </Button>
                </Upload>
                {getPrincipal().admin &&
                    <Tooltip placement="top" title={"点击搜索后再导出"}><Button onClick={this.handleExport}><Icon
                        type="export"/>导 出</Button></Tooltip>}
                {getPrincipal().admin && <Button href="/static/班列运费导入模板.xlsx" target="_blank">下载运费模板</Button>}
                {getPrincipal().admin && <Button onClick={this.handleExportTransportFee}>导出运费</Button>}
                {getPrincipal().admin && <Upload {...this.uploadTransportFeeProps}>
                    <Button disabled={importLoading}>
                        导入运费
                    </Button>
                </Upload>}
                <Button disabled={this.props.selectedRowKeys.length === 0} onClick={this.handleExportBySelect}><Icon
                    type="export"/>勾选导出</Button>
                {getPrincipal().admin ? <span>
                    <Button disabled={this.props.selectedRowKeys.length === 0} onClick={this.handleLock}><Icon
                        type="lock"/>锁定</Button>
                    <Button disabled={this.props.selectedRowKeys.length === 0} onClick={this.handleUnlock}><Icon
                        type="unlock"/>解锁</Button>
                </span> : null}
                <Switch checkedChildren="打开跟进" unCheckedChildren="关闭跟进"
                        checked={openFollow || getOpenFollow() === 'true' || getOpenFollow() === true}
                        onChange={this.onChangeFollow}/>
                <Switch style={{marginLeft: "10px"}} checkedChildren="打开待办" unCheckedChildren="关闭待办"
                        checked={this.state.daiBan === true}
                        onChange={this.onChangeDaiBan}/>
                <form
                    id="export"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/export"
                >
                    <input
                        name="userId"
                        type="hidden"
                        value={getPrincipal().id}
                    />
                    <input
                        name="columns"
                        type="hidden"
                        value={lodash.join(columns, ",")}
                    />
                    <input
                        name="table"
                        type="hidden"
                        value="zadOrder"
                    />
                    <input
                        name="openFollow"
                        type="hidden"
                        value={getOpenFollow()}
                    />
                    {data.map(item => (
                        <input
                            id={item.key}
                            name={item.key}
                            type="hidden"
                            value={item.value}
                        />
                    ))}
                </form>
                <form
                    id="exportTransportFee"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/exportTransportFee"
                >
                    <input
                        name="userId"
                        type="hidden"
                        value={getPrincipal().id}
                    />
                    <input
                        name="columns"
                        type="hidden"
                        value={lodash.join(columns, ",")}
                    />
                    <input
                        name="table"
                        type="hidden"
                        value="zadOrder"
                    />
                    <input
                        name="openFollow"
                        type="hidden"
                        value={getOpenFollow()}
                    />
                    {data.map(item => (
                        <input
                            id={item.key}
                            name={item.key}
                            type="hidden"
                            value={item.value}
                        />
                    ))}
                </form>
                <form
                    id="downloadFeeExcel"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/downloadFeeExcel"
                >
                </form>

                <form
                    id="exportBySelect"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/exportBySelect"
                >
                    <input
                        name="userId"
                        type="hidden"
                        value={getPrincipal().id}
                    />
                    <input
                        name="columns"
                        type="hidden"
                        value={lodash.join(columns, ",")}
                    />
                    <input
                        id="ids"
                        name="ids"
                        type="hidden"
                    />
                    <input
                        name="openFollow"
                        type="hidden"
                        value={getOpenFollow()}
                    />
                </form>
                <form
                    id="exportTransportFeeBySelect"
                    method="post"
                    target="_blank"
                    action="/api/zadOrder/exportTransportFeeBySelect"
                >
                    <input
                        id="idsExportTransportFee"
                        name="ids"
                        type="hidden"
                    />
                </form>
                <Modal
                    visible={this.state.visible}
                    title="导入失败详情"
                    width={'80%'}
                    onCancel={this.handleCancelModal}
                    footer={null}
                    maskClosable={false}
                >
                    <List
                        size="small"
                        header={null}
                        footer={null}
                        bordered
                        dataSource={this.state.dataList}
                        renderItem={item => <List.Item>{item}</List.Item>}
                    />
                </Modal>
            </div>

        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.zadOrder.list,
        columns: state.zadOrder.columns.columns
    };
};

export default connect(mapStateToProps)(Toolbar);
